package com.tanhua.admin.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.http.HttpResponse;
import com.tanhua.admin.service.AdminService;
import com.tanhua.model.vo.AdminVo;
import com.tanhua.model.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/system/users")
public class SystemController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //生成验证码
    @GetMapping("/verification")
    public void verification(String uuid, HttpServletResponse response) throws IOException {
        //1. 获取图片验证码对象
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(299, 97);
        //2. 获取验证码
        String code = captcha.getCode();
        //3. 存到Redis中
        redisTemplate.opsForValue().set("CODE:" + uuid, code, 3, TimeUnit.MINUTES);
        //4. 响应验证码图片（将图片数据写入响应对象中）
        captcha.write(response.getOutputStream());
    }

    //用户登录
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map map) {
        //1. 获取请求参数
        String username = map.get("username").toString();
        String password = map.get("password").toString();
        String verificationCode = map.get("verificationCode").toString();
        String uuid = map.get("uuid").toString();
        //2. 调用service方法
        Map retMap = adminService.login(username, password, verificationCode, uuid);
        //3. 返回
        return ResponseEntity.ok(retMap);
    }

    //用户基本信息
    @PostMapping("/profile")
    public ResponseEntity profile(){
        AdminVo vo = adminService.profile();
        return ResponseEntity.ok(vo);
    }


}
